package com.harvest.scientific.ladder.net

import BaseCanceledResponse
import BaseFailedResponse
import BaseResponse
import BaseSuccessResponse
/**
 * @Author: 633578
 * @Desc:  基类：请求
 */
open class BaRsitory {

    val baseService by lazy {
        BaRfit.getInstance().getService("https://test.fancyargent.com/fancyargent/", BaiService::class.java)
    }

    suspend fun <T> handleRequest(function: suspend () -> BaseResponse<T>): BaseResponse<T> {
        return runCatching {
            function.invoke()
        }.onSuccess { data: BaseResponse<T> ->
            return handleHttpOk(data)
        }.onFailure { e ->
            return handleHttpFailed(e)
        }.getOrNull() ?: BaseResponse(null)
    }

    private fun <T> handleHttpOk(data: BaseResponse<T>): BaseResponse<T> {
        return if (data is BaseCanceledResponse) {
            BaseCanceledResponse(null)
        } else if (data.success) {
            BaseSuccessResponse(data.firmSailingPublicHers)
        } else {
            handleHttpCodeError(data.furnishedLetterConnection, data.upsetTroublesomeSaturdaySecondExpense)
        }
    }

    private fun <T> handleHttpCodeError(code: Int?, msg: String?): BaseFailedResponse<T> {
        ExUtils.handleException(code, msg)
        return BaseFailedResponse(code, msg)
    }

    private fun <T> handleHttpFailed(e: Throwable): BaseResponse<T> {
        return if (e is kotlinx.coroutines.CancellationException
            || e.message?.contains(ExUtils.EX_JOB_WAS_CANCELED, ignoreCase = true) == true
            || e.message?.contains(ExUtils.EX_SOFTWARE_CONNECT_ABORT, ignoreCase = true) == true) {
            BaseCanceledResponse(null)
        } else {
            val pair = ExUtils.handleException(e)
            return if (pair.first == ExUtils.EXCEPTION_UN_KNOW_CODE) {
                BaseFailedResponse(pair.first, "")
            } else {
                BaseFailedResponse(pair.first, pair.second)
            }
        }
    }
}